<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Phoenix Live Preview Loader...</title>
    <style>
        html, body {
            margin: 0;
            padding: 0;
            height: 100%;
            overflow: hidden;
        }
        iframe {
            width: 100%;
            height: 100%;
            border: none; /* Removes the default border around an iframe */
        }
    </style>
    <style>

        .outer-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 2;
        }

        .dialog-container {
            border: 1px solid #ccc;
            background-color: #fff;
            padding: 20px;
            box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
            /* Other styles remain the same */
        }

        .dialog-title {
            font-size: 1.2em;
            margin-bottom: 10px;
        }

        .dialog-message {
            margin-bottom: 20px;
        }

        .dialog-buttons {
            text-align: right;
        }

        button {
            padding: 5px 10px;
            margin-left: 10px;
            background-color: #eee; /* Light background for buttons */
            color: #000; /* Dark text for buttons */
            border: 1px solid #ccc; /* Border for buttons */
        }

        /* Dark theme styles */
        @media (prefers-color-scheme: dark) {

            .outer-container {
                background-color: #1e1e1e; /* Dark background for the body */
                color: #ffffff; /* Light text color for dark theme */
            }

            .dialog-container {
                border: 1px solid #444; /* Darker border for the dialog */
                background-color: #2a2a2a; /* Dark background for the dialog */
            }

            button {
                background-color: #4a4a4a; /* Darker background for buttons */
                color: #fff; /* Light text for buttons */
                border: 1px solid #6a6a6a; /* Border for buttons */
            }

            button:hover {
                background-color: #5a5a5a; /* Lighter background on hover for buttons */
            }
        }

    </style>
    <script>
        const TRUSTED_ORIGINS = {
            'http://localhost:8000': true, // phcode dev server
            'http://localhost:8001': true, // phcode dev live preview server
            'http://localhost:5000': true, // playwright tests
            'http://127.0.0.1:8000': true, // phcode dev server
            'http://127.0.0.1:8001': true, // phcode dev live preview server
            'http://127.0.0.1:5000': true, // playwright tests
            'https://phcode.live': true, // phcode prod live preview server
            'https://phcode.dev': true,
            'https://dev.phcode.dev': true,
            'https://staging.phcode.dev': true,
            'https://create.phcode.dev': true
        };
        let okMessageTemplate;

        function isTrustedURL(url) {
            if(!url){
                return false;
            }
            for(let trustedUrl of Object.keys(TRUSTED_ORIGINS)){
                if(url.startsWith(trustedUrl)){
                    return true;
                }
            }
            return false;
        }

        const pageLoaderID = crypto.randomUUID();
        let securityAlertAcknowledged = false;
        let previewURL;
        let trustedProjects = [];
        let currentProjectRoot;

        function getTrustOkButton() {
            if(! okMessageTemplate){
                return "Trust Project?";
            }
            if(!currentProjectRoot){
                return okMessageTemplate.replace("{0}", "");
            }
            let projectName = currentProjectRoot;
            if(projectName.endsWith("/")){
                projectName = projectName.slice(0, -1);
            }
            projectName = projectName.split("/");
            projectName = projectName[projectName.length-1];
            return okMessageTemplate.replace("{0}", projectName);
        }

        function setupNavigationWatcher(controllingPhoenixInstanceID) {
            let livepreviewServerIframe = document.getElementById("live-preview-server-iframe");
            const LOG_LIVE_PREVIEW_KEY= "logLivePreview";
            let loggingEnabled = localStorage.getItem(LOG_LIVE_PREVIEW_KEY) || "false";
            const isLoggingEnabled = loggingEnabled.toLowerCase() === 'true';
            function _debugLog(...args) {
                if(isLoggingEnabled) {
                    console.log(...args);
                }
            }
            const LOADER_BROADCAST_ID = `live-preview-loader-${controllingPhoenixInstanceID}`;
            const navigatorChannel = new BroadcastChannel(LOADER_BROADCAST_ID);
            const LIVE_PREVIEW_MESSENGER_CHANNEL = `live-preview-messenger-${controllingPhoenixInstanceID}`;
            const phcodeBroadcastMessageChannel = new BroadcastChannel(LIVE_PREVIEW_MESSENGER_CHANNEL);
            navigatorChannel.onmessage = (event) => {
                _debugLog("Live Preview loader channel: Browser received event from Phoenix: ", JSON.stringify(event.data));
                const type = event.data.type;
                const dialog = document.getElementById('outer-container');
                switch (type) {
                    case "INITIAL_URL_NAVIGATE":
                        previewURL = event.data.URL;
                        if(!securityAlertAcknowledged || event.data.pageLoaderID !== pageLoaderID){
                            return;
                        }
                        _debugLog("initial URL page: ", previewURL);
                        // we dont need to check for trusted domain here as the live preview nav channel is only
                        // accessible by the editor domain phcode.dev/localhost etc. This page will not load any page
                        // in iframe without explicit permission grant from the editor. same for all uses below
                        document.getElementById("previewFrame").src = previewURL;
                        return;
                    case "REDIRECT_PAGE":
                        previewURL = event.data.URL;
                        if(!securityAlertAcknowledged){
                            return;
                        }
                        _debugLog("Loading page: ", previewURL);
                        if(event.data.force || document.getElementById("previewFrame").src !== previewURL) {
                            document.getElementById("previewFrame").src = previewURL;
                        }
                        return;
                    case "UPDATE_TITLE_ICON":
                        // The live preview frame will send us its title and favicon for us to set the window
                        // title and favicon. If it is that message, then, set it up
                        if(event.data.title || event.data.title === '') {
                            document.title = event.data.title;
                        }
                        if(event.data.faviconBase64){
                            // Update the favicon
                            let link = document.querySelector("link[rel~='icon']");
                            if (!link) {
                                link = document.createElement('link');
                                link.rel = 'icon';
                                document.getElementsByTagName('head')[0].appendChild(link);
                            }
                            link.href = event.data.faviconBase64;
                        }
                        return;
                    case "PROJECT_SWITCH":
                        currentProjectRoot = event.data.projectRoot;
                        document.getElementById('okButton').textContent = getTrustOkButton();
                        if(trustedProjects[currentProjectRoot] && dialog){
                            dialog.style.display = 'none';
                            document.getElementById('previewFrame').src = decodeURIComponent(previewURL);
                            securityAlertAcknowledged = true;
                            return;
                        }
                        securityAlertAcknowledged = false;
                        _debugLog("Project switched. Disable live preview tabs for security on untrusted project.");
                        document.getElementById("previewFrame").src = 'about:blank';
                        if(dialog){
                            dialog.style.display = 'flex';
                        }
                        return;
                    case 'TAB_LOADER_ONLINE': return; // loop-back message do nothing, this is for phoenix ot process.
                    default:
                    console.error("Unknown live preivew broadcast message received!: ", event);
                }
            }
            setInterval(()=>{
                // send page loader heartbeat
                navigatorChannel.postMessage({
                    type: 'TAB_LOADER_ONLINE',
                    pageLoaderID: pageLoaderID,
                    url: previewURL
                });
            }, 3000);
            navigatorChannel.postMessage({
                type: 'GET_INITIAL_URL',
                pageLoaderID: pageLoaderID
            });
            phcodeBroadcastMessageChannel.onmessage = (event) => {
                _debugLog("Live Preview message channel: Browser received event from Phoenix: ", JSON.stringify(event.data));
                if(event.data.pageLoaderID && event.data.pageLoaderID !== pageLoaderID){
                    // this message is not for this page loader window.
                    return;
                }
                // This is intended to the embedded live preview server frame which processes the request. just pass
                livepreviewServerIframe.contentWindow.postMessage(event.data.data, '*');
            }
            // These messages are sent from either the live preview frame or the server frame.
            window.addEventListener('message', function(event) {
                // Security check: ensure the message is from the expected domain
                if (!TRUSTED_ORIGINS[event.origin]) {
                    return;
                }

                // this is for phoenix to process, pass it on
                phcodeBroadcastMessageChannel.postMessage({
                    pageLoaderID: pageLoaderID,
                    data: event.data
                });
            });

            function securityOk() {
                const dialog = document.getElementById('outer-container');
                dialog.style.display = 'none';
                document.getElementById('previewFrame').src = decodeURIComponent(previewURL);
                securityAlertAcknowledged = true;
                trustedProjects[currentProjectRoot] = true;
                sessionStorage.setItem(SESSION_SECURITY_CLEAR_KEY+currentProjectRoot, 'true');
            }

            document.getElementById('okButton').addEventListener('click', function() {
                securityOk();
            });
            const SESSION_SECURITY_CLEAR_KEY = "LIVE_PREVIEW_SESSION_SECURITY_CLEAR";
            const isAck = sessionStorage.getItem(SESSION_SECURITY_CLEAR_KEY+currentProjectRoot);
            if(isAck){
                securityOk();
            }

        }

        function navigateToInitialURL() {
            const queryParams = new URLSearchParams(window.location.search);
            const phoenixInstanceID = queryParams.get('phoenixInstanceID');
            const virtualServerURL = queryParams.get('virtualServerURL');
            const localiseMessage = queryParams.get('localMessage');
            const appName = queryParams.get('appName');
            // do not pass in any live preview initial urls as it can lead to spoofing phcode.dev doamin by just
            // calling this page.
            okMessageTemplate = decodeURIComponent(queryParams.get('okMessage'));
            currentProjectRoot = queryParams.get('initialProjectRoot');

            if(!phoenixInstanceID || !virtualServerURL || !appName){
                console.error("Expected required query strings: phoenixInstanceID, virtualServerURL, appName");
                return;
            }
            setupNavigationWatcher(phoenixInstanceID);
            let livepreviewServerIframe = document.getElementById("live-preview-server-iframe");
            let serverURL = `${decodeURIComponent(virtualServerURL)}?parentOrigin=${location.origin}`;
            if(isTrustedURL(serverURL)) {
                livepreviewServerIframe.setAttribute("src", serverURL);
            }

            document.getElementById('okButton').textContent = getTrustOkButton();
            localiseMessage && (document.getElementById('dialog-message').textContent = decodeURIComponent(localiseMessage));
            appName && (document.getElementById('appName').textContent = decodeURIComponent(appName));
        }

    </script>
</head>
<body onload="navigateToInitialURL()">
    <div id="outer-container" class="outer-container">
        <div id='dialog-container' class="dialog-container">
            <div id="appName" class="dialog-title">Phoenix Code Live Preview</div>
            <div id="dialog-message" class="dialog-message">
                You are about to open an HTML file for live preview. Please proceed only if you trust the source of this project. Click 'OK' to continue, or close this window if you do not trust the source.
            </div>
            <div class="dialog-buttons">
                <button id="okButton">Trust Project</button>
            </div>
        </div>
    </div>

    <iframe id="live-preview-server-iframe"
            title="live preview server"
            src="about:blank"
            style="width:100%;"
            sandbox="allow-same-origin allow-scripts"
            hidden>
    </iframe>
    <iframe id="previewFrame"
            title="live preview"
            src="about:blank"
            sandbox="allow-same-origin allow-scripts allow-popups allow-popups-to-escape-sandbox allow-forms allow-modals allow-pointer-lock allow-downloads">
    </iframe>
</body>
</html>
